-- jump_system.lua
local JumpSystem = {}
JumpSystem.__index = JumpSystem

function JumpSystem.new(movementSystem, keyboardInput, characterMonitor)
    return setmetatable({
        movementSystem = movementSystem,
        keyboardInput = keyboardInput,
        characterMonitor = characterMonitor,
        -- 跳跃参数将在update时从Unit获取
        canDoubleJump = false,
        hasDoubleJumped = false,
        -- 状态
        jumpBuffer = 0,
        coyoteTimer = 0,
        lastGrounded = false,
        lastSpacePressed = false,
        _slopeJumpEnabled = true  -- 允许斜坡跳跃
    }, JumpSystem)
end

function JumpSystem:update(dt)
    local moveStatus = self.movementSystem:getEntityMoveStatus("player")
    if not moveStatus then return end
    
    local playerEntity = self.movementSystem:getEntity("player")
    if not playerEntity then return end
    
    -- 从Unit获取跳跃参数
    local Unit = require("Script.Unit")
    local unitInstance = self.characterMonitor:getState()
    local jumpSpeed = Unit.getJumpSpeed(unitInstance)
    local multiJumpSpeed = Unit.getMultiJumpSpeed(unitInstance)
    local jumpBufferTime = Unit.getJumpBufferTime(unitInstance)
    local coyoteTime = Unit.getCoyoteTime(unitInstance)
    
    -- 更新土狼时间（包括斜坡）
    self:_updateCoyoteTime(moveStatus, dt, coyoteTime)
    
    -- 更新跳跃缓冲
    self:_updateJumpBuffer(dt, jumpBufferTime)
    
    -- 更新二段跳状态
    self:_updateDoubleJumpState(moveStatus)
    
    -- 处理跳跃输入
    self:_handleJumpInput(playerEntity, moveStatus, jumpSpeed, multiJumpSpeed)
    
    -- 更新按键状态
    self.lastSpacePressed = self.keyboardInput:isKeyPressed("Space")
end

-- 内部：更新土狼时间（修复版，包括斜坡）
function JumpSystem:_updateCoyoteTime(moveStatus, dt, coyoteTime)
    -- 在地面或斜坡上都应该有土狼时间
    local isEffectivelyGrounded = moveStatus.isGrounded or 
                                 (moveStatus.onSlope and self._slopeJumpEnabled)
    
    if isEffectivelyGrounded then
        self.coyoteTimer = coyoteTime
        self.lastGrounded = true
    else
        if self.lastGrounded then
            self.coyoteTimer = coyoteTime
            self.lastGrounded = false
        else
            self.coyoteTimer = math.max(0, self.coyoteTimer - dt)
        end
    end
    
    -- 调试信息
    if self.movementSystem and self.movementSystem._debugGroundDetection then
        if self.frameCount and self.frameCount % 60 == 0 then
            print(string.format("土狼时间: 计时器=%.3f, 在地面=%s, 在斜坡=%s, 有效地面=%s",
                self.coyoteTimer, tostring(moveStatus.isGrounded), 
                tostring(moveStatus.onSlope), tostring(isEffectivelyGrounded)))
        end
    end
end

-- 内部：更新跳跃缓冲
function JumpSystem:_updateJumpBuffer(dt, jumpBufferTime)
    local spacePressed = self.keyboardInput:isKeyPressed("Space")
    if spacePressed then
        self.jumpBuffer = jumpBufferTime
    else
        self.jumpBuffer = math.max(0, self.jumpBuffer - dt)
    end
end

-- 内部：更新二段跳状态
function JumpSystem:_updateDoubleJumpState(moveStatus)
    -- 在地面或斜坡上时重置二段跳状态
    local isEffectivelyGrounded = moveStatus.isGrounded or 
                                 (moveStatus.onSlope and self._slopeJumpEnabled)
    
    if isEffectivelyGrounded then
        self.canDoubleJump = true
        self.hasDoubleJumped = false
    end
    
    -- 离开地面后，一旦开始一段跳就可以进行二段跳
    if not moveStatus.isGrounded and self.coyoteTimer <= 0 and not self.hasDoubleJumped then
        self.canDoubleJump = true
    end
end

-- 内部：处理跳跃输入（修复版，支持斜坡跳跃）
function JumpSystem:_handleJumpInput(playerEntity, moveStatus, jumpSpeed, multiJumpSpeed)
    local spacePressed = self.keyboardInput:isKeyPressed("Space")
    local spaceJustPressed = spacePressed and not self.lastSpacePressed
    
    -- 检查是否可以在斜坡上跳跃
    local canJumpFromSlope = moveStatus.onSlope and self._slopeJumpEnabled
    local isEffectivelyGrounded = moveStatus.isGrounded or canJumpFromSlope
    
    -- 一段跳：在地面、斜坡或土狼时间内
    if (spaceJustPressed or self.jumpBuffer > 0) and (isEffectivelyGrounded or self.coyoteTimer > 0) then
        self:_performJump(playerEntity, jumpSpeed, "first_jump")
        self.jumpBuffer = 0
        self.coyoteTimer = 0
        self.canDoubleJump = true
        self.hasDoubleJumped = false
        
        -- 通知 characterMonitor 执行跳跃
        if self.characterMonitor and self.characterMonitor.setAction then
            self.characterMonitor:setAction("jump")
        end
        
        -- 调试信息
        if self.movementSystem and self.movementSystem._debugGroundDetection then
            local jumpType = canJumpFromSlope and "斜坡跳跃" or "地面跳跃"
            print(string.format("%s成功: 速度y=%.1f, 在斜坡上=%s", 
                jumpType, jumpSpeed, tostring(moveStatus.onSlope)))
        end
    -- 二段跳：在空中且没有进行过二段跳
    elseif spaceJustPressed and self.canDoubleJump and not moveStatus.isGrounded and self.coyoteTimer <= 0 and not self.hasDoubleJumped then
        self:_performJump(playerEntity, multiJumpSpeed, "multi_jump")
        self.canDoubleJump = false
        self.hasDoubleJumped = true
        
        -- 通知 characterMonitor 执行多段跳
        if self.characterMonitor and self.characterMonitor.setAction then
            self.characterMonitor:setAction("jump")
        end
        
        -- 调试信息
        if self.movementSystem and self.movementSystem._debugGroundDetection then
            print(string.format("二段跳成功: 速度y=%.1f", multiJumpSpeed))
        end
    end
    
    -- 调试：显示跳跃状态
    if spaceJustPressed and self.movementSystem and self.movementSystem._debugGroundDetection then
        print(string.format("跳跃输入: 缓冲=%.3f, 土狼=%.3f, 在地面=%s, 在斜坡=%s, 二段跳可用=%s",
            self.jumpBuffer, self.coyoteTimer,
            tostring(moveStatus.isGrounded), tostring(moveStatus.onSlope),
            tostring(self.canDoubleJump)))
    end
end

-- 内部：执行跳跃
function JumpSystem:_performJump(playerEntity, jumpForce, jumpType)
    -- 重置Y速度，确保跳跃力度一致
    playerEntity.velocity.y = jumpForce
    
    -- 根据跳跃类型调整水平速度
    if jumpType == "first_jump" then
        -- 一段跳：保持当前水平速度
        if self.movementSystem and self.movementSystem._debugGroundDetection then
            print(string.format("执行一段跳: 力=%.1f, 当前速度x=%.1f", 
                jumpForce, playerEntity.velocity.x))
        end
    elseif jumpType == "multi_jump" then
        -- 二段跳：可以稍微调整方向
        if self.movementSystem and self.movementSystem._debugGroundDetection then
            print(string.format("执行二段跳: 力=%.1f, 当前速度x=%.1f", 
                jumpForce, playerEntity.velocity.x))
        end
    end
end

-- 强制重置跳跃状态
function JumpSystem:reset()
    self.jumpBuffer = 0
    self.coyoteTimer = 0
    self.lastGrounded = false
    self.canDoubleJump = false
    self.hasDoubleJumped = false
    self.lastSpacePressed = false
    self._slopeJumpEnabled = true
end

-- 启用/禁用斜坡跳跃
function JumpSystem:setSlopeJumpEnabled(enabled)
    self._slopeJumpEnabled = enabled
    print("斜坡跳跃: " .. (enabled and "启用" or "禁用"))
end

-- 获取跳跃状态信息
function JumpSystem:getJumpStatus()
    return {
        jumpBuffer = self.jumpBuffer,
        coyoteTimer = self.coyoteTimer,
        canDoubleJump = self.canDoubleJump,
        hasDoubleJumped = self.hasDoubleJumped,
        lastGrounded = self.lastGrounded,
        slopeJumpEnabled = self._slopeJumpEnabled
    }
end

return JumpSystem